/**
 * 上传 syncPlanByName.ts 生成的文件数据
 */

import * as fs from "fs";
import * as path from "path";

import dayjs from "dayjs";

import config from "./config";
import { calcMaterialData, uploadFile } from "./util";

import {
	planSave,
	planPage,
	materialSave,
	materialPage,
	getDeviceInfoByCode,
	planMaterialPage,
	planDevicePage
} from "./api/newApi";

(async () => {
	try {
		console.log("该脚本已经停用");
		process.exit(1);
		return;
		const officeDeviceNames: string[] = process.argv.slice(2);

		if (officeDeviceNames.length === 0) {
			console.log("请指定需要上传的文件夹名称");
			process.exit(1);
		}

		for (let i = 0; i < officeDeviceNames.length; i++) {
			const officeDeviceName = officeDeviceNames[i];
			console.log(`开始上传【${officeDeviceName}】的数据`);
			const MAP_FILE_PATH = path.resolve(config.MATERIALS_DIR, `/${officeDeviceName}/mapInfo.json`);

			if (!fs.existsSync(MAP_FILE_PATH)) {
				console.log(`没有找到对应的文件夹路径: `, MAP_FILE_PATH);
			} else {
				const content = await fs.promises.readFile(MAP_FILE_PATH);
				const mapInfo = JSON.parse(content.toString());

				const relevanceInfo: any = {};

				const nos = Object.keys(mapInfo);
				for (let ii = 0; ii < nos.length; ii++) {
					const no = nos[ii];
					const planInfo = (mapInfo as any)[no];

					if (!relevanceInfo[no]) {
						// relevanceInfo[no] = {
						// 	plans: [],
						// 	materials: [],
						// };
						relevanceInfo[no] = [];
					}
					// const planInfo = mapInfo[2372];
					const planNames = Object.keys(planInfo);
					for (let j = 0; j < planNames.length; j++) {
						const planName = planNames[j];
						const planMap = (planInfo as any)[planName];

						// 先查询有没有重复的
						const planList = await planPage(planName).then((res) => res.data?.data?.records || []);

						relevanceInfo[no][j] = {
							plan: {
								id: null
							},
							device: null,
							materials: []
						};

						relevanceInfo[no][j].device = await getDeviceInfoByCode(no).then((res) => res.data?.data || null);
						const remarks = dayjs().format("YYYY-MM-DD HH:mm:ss") + " 迁移上传";

						if (planList.length === 0) {
							console.log("上传排期数据: ", planName);
							// BUG 这里无法把7替换成0
							const playWeeks = planMap.plan.playWeeks.replace("7", "0");

							// 上传排期数据
							// TODO 后端没有返回数据
							// relevanceInfo[no][j].plan = await planSave
							await planSave({
								status: "0",
								startDate: `${planMap.plan.startDate} 00:00:00`,
								officeName: planMap.plan.officeName,
								officeCode: planMap.plan.officeId,
								createUser: "超级管理员",
								createUserName: "超级管理员",
								playWeeks,
								// startTime: planMap.plan.startTime,
								startTime: "08:00", // 固定每天 08:00
								playFrequency: "1", // 1 每天, 3 星期
								name: planName,
								endDate: `${planMap.plan.stopDate} 00:00:00`,
								remarks,
								devices: [],
								materials: []
							});
						} else {
							console.log(`【${planName}】排期数据已存在`);
							relevanceInfo[no][j].plan = planList[0];
						}

						// 重新获取排期数据
						if (!relevanceInfo[no][j].plan?.id) {
							const resList = await planPage(planName).then((res) => res.data?.data?.records || []);
							relevanceInfo[no][j].plan = resList[0];
						}
						//
						relevanceInfo[no][j].plan.remarks = remarks;

						const programNames = Object.keys(planMap.programs);
						for (let k = 0; k < programNames.length; k++) {
							const programName = programNames[k];
							const programList = (planMap.programs as any)[programName];

							for (let z = 0; z < programList.length; z++) {
								const material = programList[z];

								relevanceInfo[no][j].materials[z] = {
									id: null
								};

								const materialList = await materialPage(material.name).then((res) => res.data?.data?.records || []);
								if (materialList.length === 0) {
									console.log("上传文件: ", material.name);

									const exists = fs.existsSync(material.$fileAbsolute);
									if (!exists) {
										console.log(`文件不存在【${material.$fileAbsolute}】`);
										process.exit(1);
									}

									const fileUrl = await uploadFile(material.$fileAbsolute);

									console.log("上传素材: ", material.name);
									const stat = fs.statSync(material.$fileAbsolute);

									// TODO 后端没有返回数据
									// relevanceInfo[no][j].materials[z] = await materialSave
									await materialSave({
										...material,
										size: stat.size,
										file: fileUrl,
										remarks: remarks || "迁移上传"
									});

									// 重新获取素材数据
									if (!relevanceInfo[no][j].materials[z]?.id) {
										const resList = await materialPage(material.name).then((res) => res.data?.data?.records || []);
										relevanceInfo[no][j].materials[z] = resList[0];
									}
								} else {
									relevanceInfo[no][j].materials[z] = materialList[0];
									console.log(`【${material.name}】素材数据已存在`);
								}
							}
						}
					}
				}

				const relevanceFilePath = path.resolve(path.dirname(MAP_FILE_PATH), "relevanceInfo.json");
				await fs.promises.writeFile(relevanceFilePath, JSON.stringify(relevanceInfo, null, 2));

				planLinkDeviceAndMaterial(relevanceFilePath);
			}
		}

		console.log("success");
	} catch (err) {
		console.log("err: ", err);
	}
})();

/** 排期关联设备和素材 */
async function planLinkDeviceAndMaterial(mapFilePath: string) {
	try {
		const content = fs.readFileSync(mapFilePath);
		const relevanceFileMap = JSON.parse(content.toString());
		const nos = Object.keys(relevanceFileMap);

		for (let i = 0; i < nos.length; i++) {
			const no = nos[i];

			const noInfos = (relevanceFileMap as any)[no];
			for (let j = 0; j < noInfos.length; j++) {
				const noInfo = noInfos[j];
				// 获取原先的关联设备
				const planDeviceList = await planDevicePage(noInfo.plan.code).then((res) => {
					const list: any = res.data?.data?.records || [];
					// 排期数据在 device 里面
					return list.map((e: any) => e.device);
				});

				const idx = planDeviceList.findIndex((item: any) => item.code === noInfo.device.code);
				const name = `${noInfo.device.officeName}-${noInfo.device.name}`;
				if (idx === -1) {
					planDeviceList.push(noInfo.device);
					console.log(`【${noInfo.plan.name}】排期添加一个关联设备: `, name);
				} else {
					console.log(`【${noInfo.plan.name}】排期添加一个关联设备: `, name);
				}

				// 获取原先的关联素材
				const planMaterialList = await planMaterialPage(noInfo.plan.code).then((res) => {
					const list: any = res.data?.data?.records || [];
					// 素材数据在 material 里面
					return list.map((e: any) => e.material);
				});

				// 素材数据不存在则添加到里面去
				noInfo.materials.forEach((e: any) => {
					const idx = planMaterialList.findIndex((item: any) => item.code === e.code);
					if (idx === -1) {
						planMaterialList.push(e);
						console.log(`【${noInfo.plan.name}】排期添加一个关联素材: `, `${e.name}`);
					} else {
						console.log(`【${noInfo.plan.name}】排期已存在关联素材: `, `${e.name}`);
					}
				});

				const saveData = {
					...noInfo.plan,
					devices: planDeviceList,
					// 计算素材的开始时间和结束时间
					materials: calcMaterialData(planMaterialList, noInfo.plan.startDate, noInfo.plan.startTime)
				};

				// 保存排期
				await planSave(saveData);
				await fs.promises.writeFile(
					path.resolve(path.dirname(mapFilePath), `${saveData.name}_link.json`),
					JSON.stringify(saveData, null, 2)
				);
			}
		}

		console.log("success");
	} catch (err) {
		console.log("err: ", err);
	}
}
